import os
from datetime import timedelta
from common.deployment.paiLibrary.common.file_handler import dump_yaml_data, load_yaml_config

def get_sql_info():
    db_ip = os.getenv("DB_IP")
    db_port = int(os.getenv("DB_PORT"))
    db_user = os.getenv("DB_USER")
    db_password = os.getenv("DB_PASSWORD")

    if db_ip and  db_port and db_user and db_password:
        return "{db_user}:{db_password}@{db_ip}:{db_port}".format(
            db_user= db_user, db_password=db_password, db_ip=db_ip, db_port=db_port)

    raise  Exception("DB ENV ERROR")

class ProductConfig(object):
    SQLALCHEMY_DATABASE_URI = "mysql+pymysql://{}/management".format(get_sql_info())
    SQLALCHEMY_BINDS = {
        'management': "mysql+pymysql://{}/management".format(get_sql_info()),
        'platform': "mysql+pymysql://{}/platform".format(get_sql_info()),
        'pai': "mysql+pymysql://{}/pai".format(get_sql_info()),
        'cnbita': "mysql+pymysql://{}/cnbita".format(get_sql_info())
    }
    # SQLALCHEMY_BINDS = {
    #     'management': "mysql+pymysql://{}/management".format(get_sql_info())
    # }
    SQLALCHEMY_TRACK_MODIFICATIONS = True
    SECRET_KEY = 'super-secret'
    JWT_AUTH_HEADER_PREFIX = "Bearer"
    JWT_EXPIRATION_DELTA = timedelta(seconds=2*24*3600)

    #celery config
    CELERY_BROKER_URL = 'redis://localhost:6379/0'
    CELERY_RESULT_BACKEND = 'redis://localhost:6379/0'

def init_admin_user(db, user_shcema):
    admin_user_name = os.getenv("ADMIN_USER_NAME", "administrator@management.local")
    admin_user_password = os.getenv("ADMIN_USER_PASSWORD", "123456")
    user = None
    try:
        user = user_shcema.query.filter_by(email=admin_user_name).first()
    except Exception as err:
        print(str(err))

    db.create_all()
    db.session.commit()
    if not user:
        admin_user = user_shcema(email=admin_user_name, account="admin", role="admin")
        admin_user.password = admin_user_password
        db.session.add(admin_user)
        db.session.commit()

def init_record_event(db):

    sql_event_on = "SET GLOBAL event_scheduler = ON; "
    sql_procedure_delete = "drop procedure if exists del_record_procedure; "
    sql_procedure_create = "create procedure del_record_procedure(IN date_inter int) DELETE FROM request_record WHERE(TO_DAYS(NOW()) - TO_DAYS(FROM_UNIXTIME(unix_timestamp(create_time), '%Y%m%d'))) >= date_inter; "
    sql_event_create = "create event if not exists del_record_event on schedule every '1' DAY starts '2020-05-25 12:00:00' on completion preserve enable do CALL del_record_procedure(30);"

    ## 为什么会执行两次？？
    db.session.execute(sql_event_on)
    db.session.execute(sql_procedure_delete)
    db.session.execute(sql_procedure_create)
    db.session.execute(sql_event_create)
    db.session.commit()

def init_kube_config():
    file_dir_path = os.path.dirname(__file__)
    config_path = os.path.join(file_dir_path, "kube_config")
    k8s_api_server_url = os.environ["K8S_API_SERVER_URI"]
    kube_config_data = load_yaml_config(config_path)
    kube_config_data["clusters"][0]["cluster"]["server"] = k8s_api_server_url
    print("kube_config_data is {}".format(kube_config_data))

    dump_yaml_data(config_path, kube_config_data)
